/**
 * CustomerServlet
 * Servlet for an Ecom customer.
 * @author    Fabienne Boyer - Didier Donsez - may 2006
 */

package ecom.servlets;


import ecom.beans.entity.Productstore;
import ecom.beans.entity.Category;
import ecom.beans.entity.Clients;
import ecom.beans.entity.Commandes;
import ecom.beans.session.EcomAdminRemote;
import ecom.beans.entity.Produits;
import ecom.beans.session.CartLocal;
import ecom.beans.session.EcomCustomerRemote;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class CustomerServlet extends HttpServlet {

  /**
     * Serializable class uid.
     */
    private static final long serialVersionUID = 6893863749912962928L;
    


    /**
     * Called by the server (via the service method) to allow a servlet to
     * handle a GET request.
     * @param request an HttpServletRequest object that contains the request
     * the client has made of the servlet
     * @param response an HttpServletResponse object that contains the
     * response the servlet sends to the client
     * @throws IOException if an input or output error is detected when the
     * servlet handles the GET request
     * @throws ServletException if the request for the GET could not be handled
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
      try {
        String action = request.getParameter("action");
        if(action.equals("touslesproduits")){
           // try {
                afficherTousProduits(request, response);
           // } catch (NamingException ex) {
             //   Logger.getLogger(CustomerServlet.class.getName()).log(Level.SEVERE, null, ex);
            //}
        } else if (action.equals("authentification"))
                    {
             //try {

                 authentification(request, response);
            // } catch (NamingException ex) {
              //  Logger.getLogger(CustomerServlet.class.getName()).log(Level.SEVERE, null, ex);
                        
        } else if(action.equals("touslesmagasins")){
            //try {
                afficherMagasin(request, response);
            //} catch (NamingException ex) {
              //  Logger.getLogger(CustomerServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
        
             else if (action.equals("produitscategorie")) {
                afficherProduitsCategories(request, response);


            } else if (action.equals("authentification")) {
                authentification(request, response);


            } else if (action.equals("getProductById")){
                getProductById(request, response);

            }else if(action.equals("addProductInCard")){
               sendIdProductInJspCart(request, response);

            }else if(action.equals("deleteinCard")){
                deleteProductIncard(request,response);

            }else if(action.equals("Bycard")){
                acheterPanier(request, response);
            } else if (action.equals("listeCustomer")){

                   ListCustomer(request, response);
            }  else if(action.equals("listeProduitsA")){
                ListProduitsCategoriesbyAdmin(request, response);
            }

          else {
            System.out.println("erreur");


        }} catch (NamingException ex) {
            Logger.getLogger(CustomerServlet.class.getName()).log(Level.SEVERE, null, ex);

        

    }
       /* response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<link type=\"text/css\" href=\"../ow_jonas.css\" rel=\"stylesheet\" id=\"stylesheet\">");
        out.println("<title>");
        out.println("Customer Servlet</title>");
        out.println("</head>");
        out.println("<body style=\"background : white; color : black;\">");
        out.println("<h1>");
        out.println("Customer Servlet is not yet implemented");
        out.println("</h1>");
        out.println("</body>");
        out.println("</html>");*/
}

    private void afficherTousProduits(HttpServletRequest request, HttpServletResponse response) throws ServletException, NamingException {

        InitialContext ic = null;
        try {
            ic = new InitialContext();
        } catch (NamingException ex) {
            Logger.getLogger(CustomerServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        EcomAdminRemote admin = (EcomAdminRemote) ic.lookup(EcomAdminRemote.class.getName());

        List<Produits> lp = admin.getAllProduct();
        try {

            if (lp != null) {

                request.setAttribute("produits", lp);
                RequestDispatcher dsp = request.getRequestDispatcher("index.jsp");
                dsp.forward(request, response);

            } else {
                RequestDispatcher dsp = request.getRequestDispatcher("error.jsp");
                dsp.forward(request, response);

            }

        } catch (IOException ex) {
            Logger.getLogger(CustomerServlet.class.getName()).log(Level.SEVERE, null, ex);
        }


    
    }
    private void authentification(HttpServletRequest request, HttpServletResponse response) throws ServletException, NamingException {
        String email= request.getParameter("email");
        String mdp = request.getParameter("mdp");

        System.out.println("email "+email+" mdp " +mdp);
        InitialContext ic = null;
        try {
            ic = new InitialContext();
        } catch (NamingException ex) {
            Logger.getLogger(CustomerServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

        EcomCustomerRemote customer = (EcomCustomerRemote) ic.lookup(EcomCustomerRemote.class.getName());
        try {

            if ((customer.getAuthentication(email, mdp)) != -1) {
                // s'il est identifier , on recupere ses infos et il continu l'achat
                //request.getSession().setAttribute("customer", customer);
                System.out.println("customer.getAuthentication(email, mdp)) != -1");
                Clients client = customer.getClientsByMail(email);
                request.getSession().setAttribute("user", client);
                RequestDispatcher dsp = request.getRequestDispatcher("cart.jsp");
                dsp.forward(request, response);

            } else {
                request.setAttribute("erreur", "ERREUR");
                RequestDispatcher dsp = request.getRequestDispatcher("login.jsp");
                dsp.forward(request, response);

            }

        } catch (IOException ex) {
            Logger.getLogger(CustomerServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

    }



private void afficherMagasin(HttpServletRequest request, HttpServletResponse response) throws NamingException, ServletException
     {

        InitialContext ic = null;
        try {
            ic = new InitialContext();
        } catch (NamingException ex) {
            Logger.getLogger(CustomerServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        EcomAdminRemote admin = (EcomAdminRemote) ic.lookup(EcomAdminRemote.class.getName());

        List<Productstore> mag = admin.getAllProductStore();
        try {

            if (mag != null) {

                request.setAttribute("Magasin", mag);
                RequestDispatcher dsp = request.getRequestDispatcher("AdminMagasin.jsp");
                dsp.forward(request, response);

            } else {
                RequestDispatcher dsp = request.getRequestDispatcher("error.jsp");
                dsp.forward(request, response);

            }

        } catch (IOException ex) {
            Logger.getLogger(CustomerServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void afficherProduitsCategories(HttpServletRequest request, HttpServletResponse response) throws NamingException, ServletException {

        String numcategorie = request.getParameter("numcategorie");

        InitialContext ic = null;
        try {
            ic = new InitialContext();
        } catch (NamingException ex) {
            Logger.getLogger(CustomerServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        EcomAdminRemote admin = (EcomAdminRemote) ic.lookup(EcomAdminRemote.class.getName());

        List<Produits> lpcategories = admin.getProductsOfCategory(Long.parseLong(numcategorie));
        try {

            if (lpcategories != null) {

                request.setAttribute("produitsCategory", lpcategories);
                Category categorie = admin.getCategoryById(Long.parseLong(numcategorie));
                request.setAttribute("categorie", categorie);
                RequestDispatcher dsp = request.getRequestDispatcher("index.jsp");
                dsp.forward(request, response);

            } else {
                RequestDispatcher dsp = request.getRequestDispatcher("error.jsp");
                dsp.forward(request, response);

            }

        } catch (IOException ex) {
            Logger.getLogger(CustomerServlet.class.getName()).log(Level.SEVERE, null, ex);
        }


    }

    private void getProductById(HttpServletRequest request, HttpServletResponse response) throws NamingException, ServletException {
                InitialContext ic = null;
                String numproduit = request.getParameter("numproduit");
        try {
            ic = new InitialContext();
        } catch (NamingException ex) {
            Logger.getLogger(CustomerServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

        EcomCustomerRemote customer = (EcomCustomerRemote) ic.lookup(EcomCustomerRemote.class.getName());

        Produits p = customer.getProductById(new Long(numproduit));
        try {

            if (p != null) {

                request.setAttribute("produit", p);
                RequestDispatcher dsp = request.getRequestDispatcher("productDescription.jsp");
                dsp.forward(request, response);

            } else {
                RequestDispatcher dsp = request.getRequestDispatcher("error.jsp");
                dsp.forward(request, response);

            }

        } catch (IOException ex) {
            Logger.getLogger(CustomerServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    // insertions des produits dans le caddies
    private void sendIdProductInJspCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, NamingException {
        String numproduit = request.getParameter("numproduit");
        String qte = request.getParameter("quantite");
        System.out.println("qteeeeeeeeeeeeeeeeeeeeeeee "+qte);
         Coonteur.incNbProduct(new Long(numproduit), new Integer(qte));
         
         //List<Produits> productsIncard = customer.getProductInCart();
         //request.getSession().setAttribute("productsIncard", productsIncard);
         //request.getSession().setAttribute("conteur", Coonteur.getNbProduct());

                RequestDispatcher dsp = request.getRequestDispatcher("index.jsp");
                dsp.forward(request, response);
    }

    private void deleteProductIncard(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String  productid = request.getParameter("productid");
        String message = "suppression produit";
        request.setAttribute("messagesup", message);
        request.setAttribute("productid", productid);
        RequestDispatcher dsp = request.getRequestDispatcher("cart.jsp");
        dsp.forward(request, response);
        
    }

    private void acheterPanier(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, NamingException {

        Map<Long, Integer> lisp = (Map<Long, Integer>) request.getSession().getAttribute("listproduct");
        System.out.println("Voila le nombre de produit(s) que vous allez acheter " + lisp.size());
        String montantCaddie = request.getParameter("mc");

        //verifier si il ya un client connecte
        if (request.getSession().getAttribute("user") == null) {
            RequestDispatcher dsp = request.getRequestDispatcher("login.jsp");
            dsp.forward(request, response);
        } else {
            InitialContext ic = null;

            try {
                ic = new InitialContext();
            } catch (NamingException ex) {
                Logger.getLogger(CustomerServlet.class.getName()).log(Level.SEVERE, null, ex);
            }

            EcomCustomerRemote customer = (EcomCustomerRemote) ic.lookup(EcomCustomerRemote.class.getName());
            EcomAdminRemote admin = (EcomAdminRemote) ic.lookup(EcomAdminRemote.class.getName());

            Clients client = (Clients) request.getSession().getAttribute("user");

            System.out.println("Monsieur " + client.getNom() + " montant de votre caddie " + montantCaddie);

            int assezSurSonCompte = customer.buyCart(client.getEmail(), Double.parseDouble(montantCaddie));

            //s'il n'a pas assez sur son compte 
            if (assezSurSonCompte != 0) {
                request.setAttribute("messageCompte", "Vous n'avez pas asez d'argent pour payer");
                RequestDispatcher dsp = request.getRequestDispatcher("cart.jsp");
                dsp.forward(request, response);

            } else {

                //Insertion des lignes dans la table commande
                Commandes commande = admin.createCommande(client.getId());


                //modifier la quantite des produits
                Set cles = lisp.keySet();
                Iterator<Long> it = cles.iterator();

                while (it.hasNext()) {
                    Long cle = it.next();
                    Integer qteParProduit = lisp.get(cle);
                    Produits pr = customer.getProductById(cle);
                    pr.setQuantity(qteParProduit.toString());
                    //Insertion des lignes dans la table des achats
                    admin.createAchat(pr.getProductstore().getCity(), pr.getName(), pr.getPrice(), pr.getQuantity(), commande, pr);
                }

                request.setAttribute("messageMail", "Un mail de confirmation vous vient de vous etre envoyer");

                request.setAttribute("messageCmd", "Votre commande a été prise en compte");
                RequestDispatcher dsp = request.getRequestDispatcher("index.jsp");
                dsp.forward(request, response);
            }




        }

    }
    //////////////////////////////////Gestion des clients/////////////////////////////////////////////////////////////
    private void ListCustomer(HttpServletRequest request, HttpServletResponse response) throws NamingException, ServletException {

        String listcustomer = request.getParameter("");

        InitialContext ic = null;
        try {
            ic = new InitialContext();
        } catch (NamingException ex) {
            Logger.getLogger(CustomerServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        EcomAdminRemote admin = (EcomAdminRemote) ic.lookup(EcomAdminRemote.class.getName());

        List<Clients> lc = admin.getAllCustomer();
             
        try {
            if (lc!= null) {
                request.setAttribute("listeclients", lc);
                RequestDispatcher dsp = request.getRequestDispatcher("adminUser.jsp");
                dsp.forward(request, response);
            } else {
                RequestDispatcher dsp = request.getRequestDispatcher("error.jsp");
                dsp.forward(request, response);
            }

        } catch (IOException ex) {
            Logger.getLogger(CustomerServlet.class.getName()).log(Level.SEVERE, null, ex);
        }


    }


    /**
     * Cette méthode permet de supprimer un utilisateur de la base de données.
     * On recupere l'identifiant de la personne a supprimer puis on aura
     * une confirmation si la personne est supprimée. Sinon elle
     * va envoyer la page d'erreur.
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void supprimeUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, NamingException {

        String  iduser = request.getParameter("productid");
        String message = "L'utilisateur a été supprimé avec succès";
        request.setAttribute("MessUser", message);
        request.setAttribute("IdUser", iduser);
        RequestDispatcher dsp = request.getRequestDispatcher("supprimerClients.jsp");
        dsp.forward(request, response);


}
      private void editerUser(HttpServletRequest request, HttpServletResponse response) throws NamingException{

         String Iduser = request.getParameter("id");
         //String Iduser = request.getParameter("id");
         //String Iduser = request.getParameter("id");
         //String Iduser = request.getParameter("id");
InitialContext ic = null;
        try {
            ic = new InitialContext();
        } catch (NamingException ex) {
            Logger.getLogger(CustomerServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        EcomAdminRemote admin = (EcomAdminRemote) ic.lookup(EcomAdminRemote.class.getName());

        //admin.UpdateUser(Iduser, Iduser, Iduser, Iduser, Iduser, age);


      }
private void ListProduitsCategoriesbyAdmin(HttpServletRequest request, HttpServletResponse response) throws NamingException, ServletException {

        String numcategorie = request.getParameter("numcategorie");

        InitialContext ic = null;
        try {
            ic = new InitialContext();
        } catch (NamingException ex) {
            Logger.getLogger(CustomerServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        EcomAdminRemote admin = (EcomAdminRemote) ic.lookup(EcomAdminRemote.class.getName());

        List<Produits> lpcategories = admin.getProductsOfCategory(Long.parseLong(numcategorie));
        try {

            if (lpcategories != null) {

                request.setAttribute("produitsCategory", lpcategories);
                Category categorie = admin.getCategoryById(Long.parseLong(numcategorie));
                request.setAttribute("categorie", categorie);
                RequestDispatcher dsp = request.getRequestDispatcher("index.jsp");
                dsp.forward(request, response);

            } else {
                RequestDispatcher dsp = request.getRequestDispatcher("error.jsp");
                dsp.forward(request, response);

            }

        } catch (IOException ex) {
            Logger.getLogger(CustomerServlet.class.getName()).log(Level.SEVERE, null, ex);
        }


    }


////////////////////////////////////////////Gestion des magasins/////////////////////////////////////////////////////


}
